﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BCCommon;
using BCCommon.Enums;
using BCDto.Website.User;
using BCService.Website.User;
using BCTMSRESTful.Configs;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using Swashbuckle.AspNetCore.SwaggerGen;
using Swashbuckle.AspNetCore.Annotations;

namespace BCTMSRESTful.Controllers.Anonymous
{
    [RequireAuthorize(RoleType.User)]
#if DEBUG
    [SwaggerResponse(401, Description = "请求需要认证或者认证信息已过期。")]
    [SwaggerResponse(403, Description = "无权访问指定的功能。")]
#endif
    public class WebsiteBaseController : BCTMSRESTfulAPIController
    {
        private IRedisService redisService;
        private IUserService userService;
        /// <summary>
        /// 用户模型
        /// </summary>
        public UserDto UserInfo { get; private set; }

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            HttpContext httpContext = context.HttpContext;
            
            if (httpContext.User.Identity.IsAuthenticated && httpContext.User.Identity.Name.StartsWith("User:"))
            {
                string id = httpContext.User.Identity.Name.Substring("User:".Length);
                if (long.TryParse(id, out long userId))
                {
                    #region 初始化服务
                    redisService = httpContext.RequestServices.GetService<IRedisService>();
                    userService = httpContext.RequestServices.GetService<IUserService>();
                    #endregion
                    this.UserInfo = userService.GetUserByUserId(userId);
                }
            }
        }
    }
}
